package actor.become

import akka.actor.{Actor, ActorLogging, ActorSystem, Props, Stash}

/**
 * become/unbecome 的使用
 * Created by DJJ on 2019/12/21.
 */
object DBOActor {

  def props = Props[DBOActor]
}

sealed trait DBOperations

case class DBWrite(sql: String) extends DBOperations

case class DBRead(sql: String) extends DBOperations

sealed trait DBStates

//相当于枚举
case object Connected extends DBStates

case object Disconnected extends DBStates

class DBOActor extends Actor with ActorLogging with Stash{
  override def receive: Receive = disconnected

  def disconnected: Receive = {
    case Connected =>
      log.info("logon to db")
      context.become(connected)
      //将未连接后要处理的消息进行处理
      unstashAll()
    case _=>
      //将未连接后要处理的消息先存储起来
      //消息只有在 Connected 之后才能接收
    stash()
  }
  def connected:Receive={
    case Disconnected=>
      log.info(" logoff from db")
      //出栈,如果一直入栈,会溢出
      context.unbecome()
    case DBWrite(sql)=>
      log.info(s"DBWrite--${sql}")
    case DBRead(sql)=>
      log.info(s"DBRead--${sql}")
  }

}
object BecomeDB  extends App{


  val dbSystem = ActorSystem("dbSystem")
  val dbActor = dbSystem.actorOf(DBOActor.props,"dbActor")


  dbActor ! DBWrite("Update table x")
  dbActor ! Connected
  dbActor ! DBRead("Select from table x")
  dbActor ! Disconnected

  scala.io.StdIn.readLine()

}